package com.bawei.module_video_hall.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.bawei.lib_image.GlideApp
import com.bawei.lib_storage.database.FavoriteManager
import com.bawei.module_video_hall.R
import com.bawei.module_video_hall.databinding.ItemVideoHallRecommendBinding
import com.bawei.module_video_hall.mvi.model.RecommendVideoModelItem
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlin.math.max

/**
 *@author：lxy
 *@decription:
 *@time：2025/6/26
 */
class VideoHallAdapter(
    val list: MutableList<RecommendVideoModelItem>,
    private val coroutineScope: CoroutineScope,
    private val userId: String = "", // 默认用户ID
    private val onItemClick: ((RecommendVideoModelItem) -> Unit)? = null // 添加点击回调
) :
    RecyclerView.Adapter<VideoHallAdapter.VideoHallViewHolder>() {

    private var scrollSate = RecyclerView.SCROLL_STATE_IDLE //滚动停止

    var preloadMoreData: (() -> Unit)? = null

    var preloadEndCount = 0

    private var isReloading = false

    // 收藏状态缓存
    private val favoriteStatusMap = mutableMapOf<Int, Boolean>()

    init {
        android.util.Log.d("VideoHallAdapter", "VideoHallAdapter initialized with userId: '$userId'")
    }

    suspend fun setData(data: List<RecommendVideoModelItem>) {
        list.clear()
        list.addAll(data)
        android.util.Log.d("VideoHallAdapter", "setData called with ${data.size} items")
        
        // 先更新UI，然后延迟检查收藏状态
        notifyDataSetChanged()
        
        // 延迟检查收藏状态，确保数据库完全初始化
        delay(100) // 延迟100ms
        checkFavoriteStatus()
        notifyDataSetChanged() // 再次更新UI以显示正确的收藏状态
    }

    suspend fun addData(newData: List<RecommendVideoModelItem>) {
        val positionStart = list.size
        list.addAll(newData)
        android.util.Log.d("VideoHallAdapter", "addData called with ${newData.size} new items")
        
        // 先更新UI，然后延迟检查收藏状态
        notifyItemRangeInserted(positionStart, newData.size)
        
        // 延迟检查收藏状态，确保数据库完全初始化
        delay(100) // 延迟100ms
        checkFavoriteStatusForNewData(newData)
        notifyItemRangeChanged(positionStart, newData.size) // 更新新添加的item
    }

    inner class VideoHallViewHolder(binding: ItemVideoHallRecommendBinding) :
        ViewHolder(binding.root)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VideoHallViewHolder {
        val binding = ItemVideoHallRecommendBinding.inflate(
            LayoutInflater.from(parent.context),
            parent,
            false
        )
        return VideoHallViewHolder(binding)
    }

    override fun getItemCount(): Int {
        return list.size
    }

    override fun onBindViewHolder(holder: VideoHallViewHolder, position: Int) {
        val item = list[position]
        val binding: ItemVideoHallRecommendBinding =
            DataBindingUtil.getBinding<ItemVideoHallRecommendBinding>(holder.itemView)!!
        binding.apply {
            tvRecommendTitle.text = item.title
            tvRecommendDescription.text = item.description
            
            // 获取收藏状态并设置图标
            val isFavorite = favoriteStatusMap[item.id] ?: false
            android.util.Log.d("VideoHallAdapter", "Binding video ${item.id}, favorite status: $isFavorite")
            updateFavoriteIcon(binding, item.id, isFavorite)
            
            // 设置收藏按钮点击事件
            ivRecommendEnshrine.setOnClickListener {
                handleFavoriteClick(item, binding, position)
            }
            
            // 设置整个item的点击事件
            root.setOnClickListener {
                onItemClick?.invoke(item)
            }
        }
        GlideApp.with(holder.itemView.context).load(item.videomainimag)
            .into(binding.ivRecommendImage)

        //检查是否自动加载下一页数据
        checkPreloadMoreData(position)
    }

    private fun updateFavoriteIcon(binding: ItemVideoHallRecommendBinding, videoId: Int, isFavorite: Boolean) {
        if (isFavorite) {
            binding.ivRecommendEnshrine.setImageResource(R.drawable.baseline_star_filled_24)
        } else {
            binding.ivRecommendEnshrine.setImageResource(R.drawable.baseline_star_border_24)
        }
    }

    private fun handleFavoriteClick(item: RecommendVideoModelItem, binding: ItemVideoHallRecommendBinding, position: Int) {
        android.util.Log.d("VideoHallAdapter", "Handling favorite click for video ${item.id} with userId: $userId")
        coroutineScope.launch {
            val newFavoriteStatus = FavoriteManager.toggleFavorite(
                videoId = item.id,
                title = item.title,
                description = item.description,
                coverUrl = item.videomainimag,
                videoUrl = item.videopath,
                userId = userId
            )

            // 更新缓存状态
            favoriteStatusMap[item.id] = newFavoriteStatus
            
            // 更新UI
            withContext(Dispatchers.Main) {
                updateFavoriteIcon(binding, item.id, newFavoriteStatus)
            }
        }
    }

    private suspend fun checkFavoriteStatus() {
        android.util.Log.d("VideoHallAdapter", "Checking favorite status for ${list.size} items with userId: '$userId'")
        list.forEach { item ->
            try {
                val isFavorite = FavoriteManager.isFavorite(item.id, userId)
                favoriteStatusMap[item.id] = isFavorite
                android.util.Log.d("VideoHallAdapter", "Video ${item.id} favorite status: $isFavorite")
            } catch (e: Exception) {
                android.util.Log.e("VideoHallAdapter", "Error checking favorite status for video ${item.id}", e)
                favoriteStatusMap[item.id] = false
            }
        }
        android.util.Log.d("VideoHallAdapter", "Favorite status check completed. Map size: ${favoriteStatusMap.size}")
    }

    private suspend fun checkFavoriteStatusForNewData(newData: List<RecommendVideoModelItem>) {
        android.util.Log.d("VideoHallAdapter", "Checking favorite status for ${newData.size} new items with userId: '$userId'")
        newData.forEach { item ->
            try {
                val isFavorite = FavoriteManager.isFavorite(item.id, userId)
                favoriteStatusMap[item.id] = isFavorite
                android.util.Log.d("VideoHallAdapter", "New video ${item.id} favorite status: $isFavorite")
            } catch (e: Exception) {
                android.util.Log.e("VideoHallAdapter", "Error checking favorite status for new video ${item.id}", e)
                favoriteStatusMap[item.id] = false
            }
        }
    }

    // 测试方法：手动刷新收藏状态
    suspend fun refreshFavoriteStatus() {
        checkFavoriteStatus()
        notifyDataSetChanged()
    }

    override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
        super.onAttachedToRecyclerView(recyclerView)
        recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                scrollSate = newState
                super.onScrollStateChanged(recyclerView, newState)
            }
        })
    }

    private fun checkPreloadMoreData(position: Int) {
        if (scrollSate != RecyclerView.SCROLL_STATE_IDLE //滚动中
            && position == max(list.size - 1 - preloadEndCount, 0)
            && !isReloading
        ) {
            isReloading = true
            preloadMoreData?.invoke() //执行预加载方法
        } else {
            isReloading = false
        }
    }
}